﻿// Global vars
var FullPriceDataStore;
var FullPriceColumnModel;
var FullPriceEditorGrid;
var FullPriceWindow;

var barBtnRate;

var FullPriceSelectedRow;
var FullPriceContextMenu;

Ext.onReady(function(){
	Ext.QuickTips.init();
  	function saveItem(oGrid_event){
		var postVar = oGrid_event.record.data;
		
		Ext.Ajax.request({   
			waitMsg: 'Please wait...',
      		url: 'index.php?module=price&action=saveitem&json=1',
	  		params: postVar,
      		success: function(response){              
				var result=eval(response.responseText);
         		switch(result){
         			case 1:
            			FullPriceDataStore.commitChanges();
            			FullPriceDataStore.reload();
            			break;          
         			default:
	            		Ext.MessageBox.alert('Ошибка','Не удалось сохранить');
    	        		break;
        	 	}
      		},
      		failure: function(response){
				var result=response.responseText;
         		Ext.MessageBox.alert('error','could not connect to the database. retry later');    
      		}
   		}); 
	}
  
	function displayFormWindow(){
		if(!CreateItemWindow.isVisible()){
			resetCreateItemForm();
			CreateItemWindow.show();
		}
		else{
			CreateItemWindow.toFront();
		}
	}
  
  /*function addItemToCalc()
  {
	  var selections = FullPriceEditorGrid.selModel.getSelections();
      var prez = [];
      for(i = 0; i< FullPriceEditorGrid.selModel.getCount(); i++){prez.push(selections[i].json.article);}
      var encoded_array = Ext.encode(prez);
      Ext.Ajax.request({
         waitMsg: 'Please Wait',
         url: 'index.php?module=price&action=addtocalc&json=1', 
         params: { articles:  encoded_array }, 
         success: function(response){
           var result=eval(response.responseText);
           switch(result){
           case 1:  // Success : simply reload
             FullPriceDataStore.reload();
             break;
           default:
             Ext.MessageBox.alert('Warning','Запись не опубликована для кулькулятора');
             break;
           }
         },
         failure: function(response){
           var result=response.responseText;
           Ext.MessageBox.alert('error','Запись не опубликована для кулькулятора');      
           }
      });
  }
  */
	function confirmDeleteItem(){
		if(FullPriceEditorGrid.selModel.getCount() == 1) // only one president is selected here
		{
			Ext.MessageBox.confirm('Подтверждение','Вы действительно хотите удалить запись?', deleteItems);
		}
		else if(FullPriceEditorGrid.selModel.getCount() > 1){
			Ext.MessageBox.confirm('Подтверждение','Вы действительно хотите удалить записи?', deleteItems);
		} else {
			Ext.MessageBox.alert('Ошибка','Не выделено ни одной записи.');
		}
	}
   
	function deleteItems(btn){
		if(btn=='yes'){
         var selections = FullPriceEditorGrid.selModel.getSelections();
         var prez = [];
         for(i = 0; i< FullPriceEditorGrid.selModel.getCount(); i++){
          prez.push(selections[i].json.id);
         }
         var encoded_array = Ext.encode(prez);
         Ext.Ajax.request({  
            waitMsg: 'Please Wait',
            url: 'index.php?module=price&action=deleteitems&json=1', 
            params: { 
               ids:  encoded_array
              }, 
            success: function(response){
              var result=eval(response.responseText);
              switch(result){
              case 1:  // Success : simply reload
                FullPriceDataStore.reload();
                break;
              default:
                Ext.MessageBox.alert('Warning','Could not delete the entire selection.');
                break;
              }
            },
            failure: function(response){
              var result=response.responseText;
              Ext.MessageBox.alert('error','could not connect to the database. retry later');      
              }
			});
		}
	}

	function onFullPriceEditorGridContextMenu(grid, rowIndex, e) {
		e.stopEvent();
		var coords = e.getXY();
		FullPriceContextMenu.rowRecord = grid.store.getAt(rowIndex);
		grid.selModel.selectRow(rowIndex);
		FullPriceSelectedRow=rowIndex;
		FullPriceContextMenu.showAt([coords[0], coords[1]]);
	}
 
	function editContextMenu(){
		FullPriceEditorGrid.startEditing(FullPriceSelectedRow,1);
	}

	function deleteContextMenu(){
		confirmDeleteItem();
	}

	function printListingContextMenu(){
		printListing();
	}

  
  // << CONFIG >>
	FullPriceDataStore = new Ext.data.Store({
		id: 'FullPriceDataStore',
		proxy: new Ext.data.HttpProxy({
                url: 'index.php?module=price&action=view&json=1', 
                method: 'POST',
        }),
		reader: new Ext.data.JsonReader({
				root: 'results',
				totalProperty: 'total',
				id: 'id'
			},[ 
				{name: 'id', type: 'int', mapping: 'id'},
				{name: 'article', type: 'string', mapping: 'article'},
				{name: 'description', type: 'string', mapping: 'description'},
				{name: 'groupID', type: 'int', mapping: 'groupID'},
				{name: 'suplyPrice', type: 'float', mapping: 'suplyPrice'},
				{name: 'suplyDiscount', type: 'int', mapping: 'suplyDiscount'},
				{name: 'suplyPriceRUB', type: 'float', mapping: 'suplyPriceRUB'},
				{name: 'discount', type: 'int', mapping: 'discount'},
				{name: 'price', type: 'float', mapping: 'price'},
				{name: 'currency', type: 'string', mapping: 'currency'},
				{name: 't50', type: 'float', mapping: 't50'},
				{name: 't60', type: 'float', mapping: 't60'},
				{name: 't70', type: 'float', mapping: 't70'},
				{name: 'P', type: 'int', mapping: 'P'},
				{name: 'I', type: 'int', mapping: 'I'},
				{name: 'width', type: 'int', mapping: 'width'},
				{name: 'height', type: 'int', mapping: 'height'},
				{name: 'deep', type: 'int', mapping: 'deep'},
				{name: 'length', type: 'int', mapping: 'length'},
				{name: 'partly', type: 'int', mapping: 'partly'},
				{name: 'intercenterlen', type: 'int', mapping: 'intercenterlen'},
				{name: 'weight', type: 'float', mapping: 'weight'},
				{name: 'companyID', type: 'int', mapping: 'companyID'},
				{name: 'companyName', type: 'string', mapping: 'companyName'},
				{name: 'groupName', type: 'string', mapping: 'groupName'},
				{name: 'storageModel', mapping: 'storageModel', convert: function(v, record){return v<1 ? false : true;}}
		]),
		sortInfo:{field: 'id', direction: "ASC"}
    });
	
  GroupDataStore = new Ext.data.Store({
      id: 'GroupDataStore',
      proxy: new Ext.data.HttpProxy({
                url: 'index.php?module=price&action=viewgroup&json=1', 
                method: 'POST'
            }),
            //baseParams:{task: "LISTING_COMPANY"}, // this parameter is passed for any HTTP request
      reader: new Ext.data.JsonReader({
        root: 'results',
        totalProperty: 'total',
        id: 'id'
      },[ 
        {name: 'id', type: 'int', mapping: 'id'},
        {name: 'name', type: 'string', mapping: 'name'},
        {name: 'description', type: 'string', mapping: 'description'}
      ]),
      sortInfo:{field: 'id', direction: "ASC"}
    });
    
  FullPriceColumnModel = new Ext.grid.ColumnModel(
    [{
        header: '#',
        readOnly: true,
        dataIndex: 'id',
        width: 40,
        hidden: false
      },{
        header: 'Артикул',
        dataIndex: 'article',
        width: 120,
        editor: new Ext.form.TextField({allowBlank: false,maxLength: 255})
      },{
        header: 'Описание',
        dataIndex: 'description',
        width: 180,
        editor: new Ext.form.TextField({allowBlank: true}),
      },{
        header: 'groupID',
        readOnly: true,
        dataIndex: 'groupID',
        width: 50,       
        hidden: true
      },{
          header: 'Группа',
          dataIndex: 'groupName',
          width: 150,
          editor: new Ext.form.ComboBox({
                 //typeAhead: true,
                 triggerAction: 'all',
                 store:GroupDataStore,
                 mode: 'remote',
                 displayField: 'name',
                 valueField: 'id',
                 lazyRender:true,
                 listClass: 'x-combo-list-small',
                 selectOnFocus:true
              })
      },{
        header: 'Розн.&euro;',
        dataIndex: 'suplyPrice',
        width: 50,
        editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})
      },{
        header: 'Скидка опт.',
        dataIndex: 'suplyDiscount',
        width: 50,
		hidden: true,
        editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})
	  },{
        header: 'Опт. руб.',
        readOnly: true,
        dataIndex: 'suplyPriceRUB',
        width: 55,
		css: 'font-weight: bold;'
      },{
        header: 'Скидка',
        dataIndex: 'discount',
        width: 50,
        editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})
      },{
        header: 'Цена',
        dataIndex: 'price',
        width: 50,
		css: 'font-weight: bold;',
        editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})
      },{
        header: "Валюта",
        dataIndex: 'currency',
        width: 50,
		hidden: true
      },{
		header: "companyID",
        dataIndex: 'companyID',
        width: 70,
		hidden: true
	  },{
        header: 'Фабрика',
        dataIndex: 'companyName',
        width: 150,
        editor: new Ext.form.ComboBox({
               //typeAhead: true,
               triggerAction: 'all',
               store:CompaniesDataStore,
               mode: 'remote',
               displayField: 'name',
               valueField: 'id',
               lazyRender:true,
               listClass: 'x-combo-list-small',
			   selectOnFocus:true
            })
      },
	  { header: "Склад", dataIndex: 'storageModel', width: 43, xtype:'booleancolumn', trueText: 'Да', falseText: "Нет", editor: new Ext.form.Checkbox({checked: false, inputValue : '1'})},
	  
	  { header: "&#x0394;T50", dataIndex: 't50', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11})},
	  { header: "&#x0394;T60", dataIndex: 't60', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "&#x0394;T70", dataIndex: 't70', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Эл. мощ, Вт", dataIndex: 'P', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Ток, А", dataIndex: 'I', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Ширина, мм", dataIndex: 'width', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Высота, мм", dataIndex: 'height', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Глубина, мм", dataIndex: 'deep', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Длина, мм", dataIndex: 'length', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "partly", dataIndex: 'partly', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Межцентр., мм", dataIndex: 'intercenterlen', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) },
	  { header: "Вес, кг", dataIndex: 'weight', width: 50, editor: new Ext.form.NumberField({allowBlank: false,allowDecimals: true,allowNegative: false,blankText: '0',maxLength: 11}) }
	  ]
    );
    FullPriceColumnModel.defaultSortable= true;
    
	barBtnRate=new Ext.Button({text: 'Курс: '})
    
FullPriceEditorGrid =  new Ext.grid.EditorGridPanel({
	id: 'FullPriceEditorGrid',
	store: FullPriceDataStore,
	cm: FullPriceColumnModel,
	enableColLock:false,
	clicksToEdit:2,
	selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
	bbar: new Ext.PagingToolbar({
	        pageSize: 15,
	        store: FullPriceDataStore,
	        displayInfo: true
	    }),
	tbar: [
	  {
	    text: 'Добавить',
	    tooltip: 'Добавить новую запись',
	    iconCls:'add',                      // reference to our css
	    handler: displayFormWindow
	  }, '-', { 
	    text: 'Удалить запись',
	    tooltip: 'Уделение выделенной записи',
	    handler: confirmDeleteItem,   // Confirm before deleting
	    iconCls:'remove'
	  }, '-', new Ext.app.SearchField({
	            store: FullPriceDataStore,
	            params: {start: 0, limit: 15},
	            width: 120})
	  ,'-', { 
	      text: 'Обновить цены',
	      tooltip: 'Обновить цены с учетом курса',
	      handler: function() {RefreshPriceWindow.show();},
	      iconCls:'add'
	  }, barBtnRate
	]
});
	
  FullPriceEditorGrid.addListener('rowcontextmenu', onFullPriceEditorGridContextMenu);

  FullPriceContextMenu = new Ext.menu.Menu({
      id: 'FullPriceEditorGridContextMenu',
      items: [
	  { text: 'Добавить в заказ', handler: addToOrder },
      { text: 'Изменить', handler: editContextMenu },
      { text: 'Удалить', handler: deleteContextMenu },
      '-',
      { text: 'Распечатать', handler: printListingContextMenu }
      ]
   });    
    
  FullPriceWindow = new Ext.Window({
      id: 'FullPriceWindow',
      title: 'Прайс лист',
      closable:true,
      width:800,
      height:460,
      plain:true,
      layout: 'fit',
      items: FullPriceEditorGrid
    });
	
	//alert(document.currencyCode);
	var dr=Ext.util.Cookies.get('rate');
	if (dr!=null) defaultRate = dr;
	
	Ext.Ajax.request({
  		waitMsg: 'Please wait...',
  		url: 'index.php?module=price&action=getrate&json=1',
  		params: {currency_code: currencyCode},
  		success: function(response){
     		var result=eval(response.responseText);
			var rate_val = ((result.failure!=null)&& result.failure) ? defaultRate : result.rate*rateK;
			if (rate_val<0) rate_val = defaultRate; else Ext.util.Cookies.set('rate',rate_val);
			FullPriceDataStore.setBaseParam('rate',rate_val);
			FullPriceDataStore.load({params: {start: 0, limit: 15}});
			barBtnRate.setText('Курс: '+rate_val);
  		},
  		failure: function(response){
     		var result=response.responseText;
			FullPriceDataStore.setBaseParam('rate',defaultRate*rateK);
			FullPriceDataStore.load({params: {start: 0, limit: 15}});
			barBtnRate.setText('Курс: '+defaultRate*rateK);
     		Ext.MessageBox.alert('error','Не удалось получить курс ЦБ');
  		}
	});

	//FullPriceDataStore.load({params: {start: 0, limit: 15}});
	FullPriceWindow.show();
	FullPriceEditorGrid.on('afteredit', saveItem);
});